<template>
  <div class="page-model">
    <el-dialog
      :before-close="beforeClose"
      v-model="isShow"
      title="Warning"
      width="40%"
      center
    >
      <my-Form
        v-bind="modelConfig"
        :modelValue="value"
        @update:modelValue="valueChange"
      />

      <slot />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">Cancel</el-button>
          <el-button :loading="loading" type="primary" @click="handlerConfirm">
            Confirm
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, PropType, ref } from 'vue';
import { useStore } from '@/store';
import type { IForm } from '@/components/myForm/types/index';

import myForm from '@/components/myForm/myForm.vue';

export default defineComponent({
  props: {
    modelConfig: {
      type: Object as PropType<IForm>,
      required: true,
    },

    value: {
      type: Object,
      default: () => ({}),
    },

    pageName: {
      type: String,
      required: true,
    },

    rowId: null,
  },

  emits: ['update:value', 'update:show', 'confirm'],

  setup(props, ctx) {
    const { emit } = ctx;
    const loading = ref(false);
    const store = useStore();

    const valueChange = (value) => {
      emit('update:value', { ...value });
    };

    const isShow = ref(false);
    const closeDialog = function () {
      if (!loading.value) {
        isShow.value = false;
      }
    };

    const show = function () {
      isShow.value = true;
    };

    const handlerConfirm = function () {
      const value = { ...props.value };
      const id = props.rowId;
      const pageName = props.pageName;

      // 编辑
      if (id) {
        store.dispatch('system/editPageDataAction', {
          pageName,
          id,
          editData: value,
        });
      } else {
        // 新增
        store.dispatch('system/createPageDataAction', {
          pageName,
          newData: value,
        });
      }
    };

    const beforeClose = function (done) {
      if (!loading.value) {
        done();
      }
    };

    return {
      loading,
      valueChange,
      closeDialog,
      show,
      isShow,

      handlerConfirm,
      beforeClose,
    };
  },

  components: {
    myForm,
  },
});
</script>
